package com.itbaizhan;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/*图片或者文件要放在web根目录下，不可以在WEB_INF目录下
* 因为新添加了图片，tomcat可能读取不到，所以要tomcat/web下的项目目录把这个目录删除，再重新启动tomcat加载目录*/
public class ServletContextDown extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取ServletContext对象  已经在容器中实例化，不用我们实化
        ServletContext servletContext = this.getServletContext();
        //路径转换  相对路径转为绝对路径  因为下面的File
        // 要绝对路径才能跨平台用（例：linux）
        String realpath = servletContext.getRealPath("image/端砚.jpg");
        System.out.println(realpath);
        File file = new File(realpath);
        InputStream is = new FileInputStream(file);
        byte[] buff = new byte[is.available()];
        is.read(buff);

        //设置响应编码
        resp.addHeader("Content-Disposition","attachment;filename="+new String(file.getName().getBytes("gbk"),"iso-8859-1"));
        OutputStream os = resp.getOutputStream();
        os.write(buff);
        os.flush();
        os.close();


    }
}
